<template>
	<!-- 申请车位-第一步关联小区选中 -->
	<view>
		<view class="head-block" v-if="weixin == 2">
				     <view class="nav-title" :style="'top:10px'"></view>
					 <!-- 返回 -->
					 <view class="icon" @tap="goMy" :style="'top:6px'">
					      <van-icon name="arrow-left" color="#333" size="45rpx" />
					  </view>
				 </view>
		<!-- 头部进度条 -->
		<view class="step-top">
			<view class="stepper">
				<view class="step-icon">
					<image src="../../static/assets/img/sucess.png" mode="widthFix"></image>
				</view>
			</view>
			<view class="line"></view>
			<!-- <view class="stepper">
            <view wx:if="{{curStep==1}}" class="step-circle"></view>
            <view class="step-icon" wx:else>
                <image src="/assets/img/sucess.png"></image>
            </view>
        </view>
        <view class="line"></view> -->
			<view class="stepper">
				<view v-if="curStep != 3" class="step-circle"></view>
				<view class="step-icon" v-else>
					<image src="../../static/assets/img/sucess.png" mode="widthFix"></image>
				</view>
				<view></view>
			</view>
		</view>
		<view class="step-btm">
			<view class="step-title">身份认证</view>
			<!-- <view class="step-title {{curStep==1?'graytitle':''}}">配置收款账户</view> -->
			<view :class="'step-title ' + (curStep != 3 ? 'graytitle' : '')">完成</view>
		</view>
		<!-- 第一步提交车位资料 -->
		<view v-if="curStep == 1" class="step-first">
			<view class="input-title">选择小区</view>
			<view class="input-box">
				<input @tap="inputMapname" v-model="name" maxlength="12" placeholder="请输入" readonly="readonly" />
			</view>
			<view class="input-title">请填写您的车位号</view>
			<view class="input-box">
				<input @confirm="inputSpaceNo" @blur="inputSpaceNo" confirm-type="done" maxlength="12"
					placeholder="请输入" />
			</view>
			<view class="input-title">上传有效证明，便于快速审核（非必填）</view>
			<view class="upload-area">
				<view class="imag-box-list">
					<view class="img-content" v-for="(item,index) in fileList" :key="index">
						<image class="up-icon" :src="item.url" lazy-load="true" mode="aspectFit"></image>
						<image class="up-icon1" @click="cancelicon(index)"
							src="https://lebonbon.oss-cn-hangzhou.aliyuncs.com/UI/icons/cancelicon.png" lazy-load="true"
							mode="aspectFit"></image>
					</view>
					<view class="img-content skin-border" @click="uplodaImg" v-if="isAllowUpImage">
						<view class="upload-box">
							<image src="../../static/assets/img/add.png" mode="widthFix"></image>
						</view>
					</view>
				</view>
			</view>
			<view class="upload-tip">最多可上传三张图片</view>
			<view class="btn-green btn-step2" @tap="nextStep">提交</view>
			<!-- <view class="btn-gray" bindtap="skip">跳过</view> -->
		</view>
		<!-- 第二步设置收款 -->
		<view v-if="curStep == 2" class="step-first">
			<image class="mid-icon" src="../../static/assets/img/img01.png" mode="widthFix"></image>
			<view class="input-title">设置收款账号</view>
			<view class="btn-green" @tap="nextStep">下一步</view>
		</view>
		<!-- 第三步完成 -->
		<view v-if="curStep == 3" class="step-first">
			<image src="../../static/assets/img/waiting.png" class="step3-img"></image>
			<view class="step3-tip">资料已提交审核，请稍后</view>
			<view class="btn-gray" @tap="complete">完成</view>
		</view>
	</view>
	<!-- 小区选择下拉 -->
	<!-- <van-popup show="{{ show }}" position="bottom" bind:close="onClose">
    <van-picker show-toolbar columns="{{ columns }}" bind:cancel="onCancel" bind:confirm="onConfirm" bind:change="onChange" />
</van-popup> -->
</template>

<script>
	// pages/applyStep1/applyStep1.js
	import util from './../../utils/util.js';
	import api from './../../utils/api.js';
	import {
		Dialog
	} from 'vant';
	export default {
		data() {
			return {
				columns: [],
				list: [],

				//关联小区
				show: false,

				curStep: 1,

				//1,2 ,3当前第几步
				show: false,

				//小区选择pop
				columns: [],

				//下拉小区列
				community: {
					unitName: '君景亭'
				},

				//当前选的小区
				parkingNumber: '',

				//车位号
				picUrlList: [],

				//证明材料
				fileList: [],

				mapname: {},
				name: '',
				parkingCode: '',
				type: 0,
				isAllowUpImage: true,
				weixin:uni.getStorageSync('weixin')
			};
		}
		/**
		 * 生命周期函数--监听页面加载
		 */
		,
		onLoad: function(options) {
			this.getList();
			uni.removeStorageSync('searchHistory');
			uni.removeStorageSync('isSearching'); //查询完就移除掉、
		},
		/**
		 * 生命周期函数--监听页面初次渲染完成
		 */
		onReady: function() {},
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: function() {
			if (Object.keys(this.mapname).length > 0) {
				let name = this.mapname.name;
				this.setData({
					name: name,
					list: [],
					type: 2
				});
			}
		},
		/**
		 * 生命周期函数--监听页面隐藏
		 */
		onHide: function() {},
		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload: function() {},
		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh: function() {},
		/**
		 * 页面上拉触底事件的处理函数
		 */
		// onShareAppMessage: function () {
		// }
		onReachBottom: function() {},
		/**
		 * 用户点击右上角分享
		 */
		methods: {
			goMy() {
					     uni.navigateBack({
					         delta: 1
					     });
					 },
			// 下一步
			nextStep() {
				if (this.curStep == 1) {
					// if(!this.data.community.unitName){
					//   wx.showToast({
					//     title: '请选择小区名称!',
					//     icon:'none'
					//   })
					// }else{
					//   this.setData({
					//     curStep: 2
					//   })
					// }
					// }else{
					// 判断必填项有没有填写
					if (this.name == '') {
						uni.showToast({
							title: '请填写小区!',
							icon: 'none'
						});
						return;
					} else if (this.parkingNumber == '') {
						uni.showToast({
							title: '请填写车位号!',
							icon: 'none'
						});
						return;
					} // else if(this.data.picUrlList.length==0){
					//   wx.showToast({
					//     title: '请上传至少一张有效证明!',
					//     icon:'none'
					//   })
					//   return;
					// }
					else {
						// 不跳过的话 只需要调用此接口,将关联小区与车位申请二合一了
						this.applyParkingSpace(); // this.setData({
						//   curStep: 3
						// })
					} // this.applyParkingSpace()
				}
			},

			// 跳过--提交小区
			skip() {
				// this.getcommitMyUnit()
				// 看这个写在哪里
				this.setData({
					curStep: 3
				});
			},

			// 点完成跳转
			complete() {
				uni.switchTab({
					url: '../home/index'
				});
			},

			// 点击选择小区
			showSelectbox() {
				this.setData({
					show: true
				});
			},

			// 提交关联小区
			getcommitMyUnit() {
				const unionId = uni.getStorageSync('unionId') || '';
				util.request(api.commitMyUnit + '?userUnionId=' + unionId + '&unitCode=' + this.community.unitCode, 'get')
					.then((res) => {
						if (res.code == 0) {
							uni.showToast({
								title: '申请成功',
								icon: 'success'
							});
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							});
						}
					})
					.catch((err) => {
						uni.showToast({
							title: '接口出错了...',
							icon: 'none'
						});
					});
			},

			// 提交车位资料
			applyParkingSpace() {
				let param = {
					userUnionId: uni.getStorageSync('unionId'),
					parkingNumber: this.parkingNumber,
					parkingCode: this.parkingCode,
					// "communityCode": "111",
					picUrlList: this.picUrlList
				};
				util.request(api.applyParkingSpaceNew, param, 'POST')
					.then((res) => {
						if (res.success) {
							this.setData({
								curStep: 3
							});
						} else {
							uni.showToast({
								title: res.msg || '提交失败',
								icon: 'none'
							});
						}
					})
					.catch((err) => {
						console.log(err);
						uni.showToast({
							title: '接口出错了...',
							icon: 'none'
						});
					});
			},

			//查询小区下拉
			getList() {
				const param = {
					communityCode: '111',
					unitName: '',
					isOpen: 1,
					pageInfo: {
						pageNumber: 1,
						pageSize: 100
					}
				};
				util.request(api.list, param, 'POST').then((res) => {
					if (res.code == 0) {
						var array = [];

						if (res.data.content) {
							res.data.content.map((e, index) => {
								array.push(
									Object.assign({}, e, {
										text: e.unitName
									})
								);
							});
						}

						array.push({
							text: '+未发现我的小区'
						});
						this.setData({
							columns: array
						});
					}
				});
			},

			onClose() {
				this.setData({
					show: false
				});
			},

			onChange(event) {
				const {
					picker,
					value,
					index
				} = event.detail; // console.log(picker, value, index);
				// Toast(`当前值：${value}, 当前索引：${index}`);
			},

			// 下拉框选择
			// onConfirm(e) {
			//   console.log(e);
			//   if (e.detail.value.text === "+未发现我的小区") {
			//     // 跳转单独申请小区名称页面
			//     wx.navigateTo({
			//       url: '../applyCommunity/applyCommunity',
			//     })
			//   } else {
			//     this.setData({
			//       community: {
			//         unitName: e.detail.value.unitName,
			//         unitCode: e.detail.value.unitCode
			//       }
			//     })
			//     // this.getcommitMyUnit(e.detail.value.unitCode);
			//   }
			//   this.setData({
			//     show: false
			//   });
			// },
			onCancel() {
				this.setData({
					show: false
				});
			},

			inputMapname(e) {
				uni.navigateTo({
					url: '../community2/index' + "?url='applyStep1'"
				});
			},

			// 第二步输入框
			inputSpaceNo(e) {
				this.setData({
					parkingNumber: e.detail.value
				});
			},
			// 删除图片凭证
			cancelicon(index) {
				let t = this;
				t.fileList.splice(index, 1);
				if (t.fileList.length < 3) {
					t.isAllowUpImage = true;
				}
			},			
			uplodaImg() {
				let that = this;
				uni.chooseImage({
					count: 1, // 默认最多一次选择9张图
					success: res => {
						var token = uni.getStorageSync('currentRole').token
						uni.showLoading()
						uni.uploadFile({
							url: api.vueUpload,
							filePath: res.tempFilePaths[0],
							name: 'file',
							formData: {
								user: 'test'
							},
							header: {
								Authorization: uni.getStorageSync('AUTHORIZATION') //如果需要token的话要传
							},
							success: item => {
								if (item.statusCode == 200) {
									var data = JSON.parse(item.data);
									let pic = that.picUrlList;
									pic.push(data.data);
									that.setData({
										picUrlList: pic
									});
									uni.showToast({
										title: '上传成功'
									})
									if (that.picUrlList.length == 3) {
										that.isAllowUpImage = false;
									}
									if (that.picUrlList.length > 3) {
										uni.showToast({
											mask: true,
											title: "最多上传3张",
											icon: "none"
										})
										return;
									}
									if (data.data) {
										util.request(api.getEncryPath + '?path=' + data.data, '', 'POST').then((res) => {
											let arr = that.fileList;
											arr.push({
												url: res
											});
											that.setData({
												fileList: arr
											});
										});
									}
								} else {
									uni.showToast({
										title: '上传失败，请重新上传',
										icon: 'error'
									})
								}
							},
							fail: (err) => {
								console.log('uploadImage fail', err);
								uni.showToast({
									title: '上传失败，请重新上传',
									icon: 'error'
								})
							}
						})
					}
				})
			},
			// 第二步上传
			afterRead(event) {
				const {
					file
				} = event.detail; // this.setData({ fileList: event.detail.file.url });
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式

				var that = this; //坑1： this需要这么处理

				uni.uploadFile({
					url: api.vueUpload,
					// 仅为示例，非真实的接口地址
					filePath: file.url,
					name: 'file',
					formData: {
						user: 'test'
					},
					header: {
						Authorization: uni.getStorageSync('AUTHORIZATION') //如果需要token的话要传
					},

					success(res) {
						var data = JSON.parse(res.data);
						let pic = that.picUrlList;
						pic.push(data.data);
						that.setData({
							picUrlList: pic
						});

						if (data.data) {
							util.request(api.getEncryPath + '?path=' + data.data, '', 'POST').then((res) => {
								let arr = that.fileList;
								arr.push({
									url: res
								});
								that.setData({
									fileList: arr
								});
							});
						}
					}
				});
			},

			deleteFun(e) {
				let del = e.detail.index;
				let file = this.fileList;
				let pic = this.picUrlList;
				file.splice(del, 1);
				pic.splice(del, 1);
				this.setData({
					fileList: file,
					picUrlList: pic
				});
			}
		}
	};
</script>
<style>
	@import './applyStep1.css';
</style>
